package com.goresor.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.goresor.model.User;

@Repository
public class GoResorJdbcDaoImpl extends JdbcDaoSupport implements IGoResorJdbcDao {

	private static final String USER_AUTHORITY = "ROLE_USER";

	@Autowired
	private DataSource dataSource;

	@PostConstruct
	private void init() {
		setDataSource(dataSource);
	}

	@Transactional
	public void createUser(String username, String password, String email) {
		getJdbcTemplate().update("insert into users(username, password,enabled) values (?,?,true)", username, password);
		getJdbcTemplate().update("insert into authorities(username,authority) values (?,?)", username, USER_AUTHORITY);
	}

	@Override
	public UserDetails getUser(final String username) {
		List<UserDetails> users =  getJdbcTemplate().query(
				"select password,enabled,authority from users u, authorities a where a.username=u.username and u.username=?",
				new Object[] { username }, new RowMapper<UserDetails>() {
					@Override
					public UserDetails mapRow(ResultSet rs, int rowNum) throws SQLException {
						User user = new User();
						user.setPassword(rs.getString(1));
						user.setEnabled(rs.getBoolean(2));
						user.addAuthorities(rs.getString(3).split(","));
						return user;
					}
				});
		if(users.size()==0 || users.size()>1){
			return null;
		}
		else{
			return users.get(0);
		}
	}
}
